<template>
  <div class="home">
    <van-tabs>
      <van-tab v-for="category in categoryList" :title="category.name" :key="category.id"></van-tab>
    </van-tabs>
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item
        v-for="banner in bannerList"
        :key="banner.id"
      >
        <img :src="banner.imageUrl" alt="">
      </van-swipe-item>
    </van-swipe>
    <van-divider>爆款商品</van-divider>
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <van-card
        v-for="item in baoKuanList"
        :key="item.id"
        :price="item.price"
        :origin-price="item.originPrice"
        :title="item.title"
        :thumb="item.image"
        @click="$router.push('/detail/?id=' + item.id)"
      >
        <template #num>
          <div class="car">
            月销售量: {{item.saleNum}}
            <van-icon
             name="shopping-cart-o"
             size="18"
             color="red"
             @click.stop="handleAddCart(item)"
             />
          </div>
        </template>
        <template #desc>
          <div class="rank">排行: {{item.rankingTag}}</div>
        </template>
      </van-card>
    </van-list>
  </div>
</template>

<script>
import { getCategories, getBaoKuanItems, getBanners } from '@/api/home'
import { mapMutations } from 'vuex'
export default {
  name: 'Home',
  data () {
    return {
      categoryList: [],
      baoKuanList: [],
      bannerList: [],
      finished: false,
      loading: false,
      nextIndex: 0
    }
  },
  async created () {
    const p1 = getCategories()
    const categories = await p1
    this.categoryList = categories.list
    const result = await getBanners()
    this.bannerList = result.banners
  },
  methods: {
    ...mapMutations(['addToCart']),
    async onLoad () {
      const p2 = getBaoKuanItems(this.nextIndex)
      const baokuans = await p2
      this.baoKuanList.push(...baokuans.list)
      this.finished = baokuans.isEnd
      this.nextIndex = baokuans.nextIndex
      this.loading = false
    },
    handleAddCart (prod) {
      const { id, image, title, price } = prod
      this.addToCart({
        id,
        image,
        title,
        price,
        amount: 1
      })
    }
  }
}
</script>

<style lang="less" scoped>
.rank {
  color: red;
}
.my-swipe .van-swipe-item {
  margin-top: 4px;
  img{
    width: 100%;
  }
}
.car {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
</style>
